package com.grapes.business;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Connection {
	private String HOST = "http://sos.abita.com/";
	public static int HPPT_POST_OK = 200;
	public static int RESULT_CODE_OK=1;
	public static int RESULT_CODE_FAIL=0;
	public static int RESULT_CODE_TOKEN_EXPIRE=2;
	
    public static String BIZ_GET_CAMPUST_TALKING_LIST="meeting_list.aspx";
    public static String BIZ_GET_NET_APPLICATION_LIST="online_application_list.aspx";
    public static String BIZ_GET_DAILY_INFO_LIST="recruit_info_list.aspx";
    
    public static String BIZ_SUBMIT_PERSONAL_ACTIVITY="submit_personal_activity.aspx";
    public static String BIZ_GET_PERSONAL_ACTIVITY_LIST="personal_activity_list.aspx";
    
    public static String BIZ_GET_COMPANY_CAMPUS_TALKING_LIST="company_meetings.aspx";
    public static String BIZ_GET_COMPANY_NET_APPLICATION="company_online_application.aspx";
    public static String BIZ_GET_COMPANY_POSITION_LIST="get_recruit_info.aspx";
    public static String BIZ_GET_COMPANY_FOLLOWER_LIST="company_follwers.aspx";
    public static String BIZ_GET_COMPANY_TOPIC_LIST="company_topic_list.aspx";
    
    public static String BIZ_GET_GLOBAL_TOPIC_LIST="global_topic_list.aspx";
    public static String BIZ_SUBMIT_TOPIC="submit_topic.aspx";
    public static String BIZ_SUBMIT_REPLAY_FOR_TOPIC="submit_reply_for_topic.aspx";
    
    public static String BIZ_SUBMIT_RERSONAL_MAJOR="submit_personal_major.aspx";
    public static String BIZ_GET_PERSONAL_MAJOR="get_personal_major.aspx";
    
    private String token="";
    
    private static Connection instance;
    
    private Connection(){}
    
    public static Connection getInstance()
    {
    	if(instance==null)
    		instance=new Connection();
    	return instance;
    }
    
	public String executeHttpGet(String bizCode, Map<String, String> params) {
		String result = "";
		URL url = null;
		try {
			url = new URL(generateURL(bizCode, params));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		HttpURLConnection con = null;
		BufferedReader reader = null;
		if (null != url) {
			try {
				con = (HttpURLConnection) url.openConnection();
				InputStreamReader isr = new InputStreamReader(
						con.getInputStream());
				reader = new BufferedReader(isr);
				String inputLine = "";
				while ((inputLine = reader.readLine()) != null)
					result += inputLine;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				con.disconnect();
				try {
					if (null != reader)
						reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
        //process when token expire.
		try {
			JSONObject jsonObj=new JSONObject(result);
			token=jsonObj.getString("token");            
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	public int executeHttpPost(String bizCode, Map<String, String> params) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(HOST +bizCode);
		HttpResponse response = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
					params.size());
			Iterator<String> it = params.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				nameValuePairs
						.add(new BasicNameValuePair(key, params.get(key)));
			}
			nameValuePairs.add(new BasicNameValuePair("token", token));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			response = httpclient.execute(httppost);
			return response.getStatusLine().getStatusCode();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return -1;
	}

	/*
	 * 根据业务号BizCode和所需参数params生成相应url请求字符串
	 * 
	 * @param BizCode 业务号
	 * 
	 * @param params 调用服务时所需参数
	 * 
	 * @return url请求字符串
	 */
	private String generateURL(String BizCode, Map<String, String> params) {
		if(null==params||params.keySet().size()==0)
			return BizCode;
		StringBuffer urlBuffer = new StringBuffer(HOST + (String) BizCode);
		Iterator<String> keys = params.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			urlBuffer.append("&").append(key).append("=")
					.append(params.get(key));
		}
		String url = urlBuffer.toString();
		url = url.substring(0, url.indexOf("&"))
				+ url.substring(url.indexOf("&") + 1);
		url=url+"&token="+token;
		Log.d("Abita URL:", url);
		return url;
	}
}
